﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

namespace MyWeb.Common.Helper
{
    public static class XmlSerializeHelper
    {
        /// <summary>
        /// 实体类转SoapXML
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static string SoapXmlSerialize<T>(T obj)
        {
            try
            {
                using (StringWriter sw = new StringWriter())
                {

                    //XmlTypeMapping myTypeMapping = new SoapReflectionImporter().ImportTypeMapping(obj.GetType());
                    //XmlSerializer serialize = new XmlSerializer(myTypeMapping);
                    //serialize.Serialize(sw, obj);

                    XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
                    namespaces.Add("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
                    namespaces.Add("urn", "urn:sap-com:document:sap:rfc:functions");
                    XmlSerializer serialize = new XmlSerializer(obj.GetType());

                    serialize.Serialize(sw, obj, namespaces);

                    //serialize.Serialize(sw, obj);
                    sw.Close();

                    return sw.ToString();
                }
            }
            catch(Exception ex)
            {
                throw new Exception("将实体对象转换成XML异常",ex);
            }
        }

        public static T DeSerializer<T>(string strXML) where T:class
        {
            try
            {
                using (StringReader sr = new StringReader(strXML))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    return serializer.Deserialize(sr) as T;
                }
            }
            catch(Exception ex)
            {
                throw new Exception("将XML转成实体对象异常", ex);
            }
        }
    }
}
